﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Omu.AwesomeDemo.Core.Model;
using Omu.AwesomeDemo.Core.Repository;

namespace Omu.AwesomeDemo.WebUI.Controllers
{
    public class CountryAjaxDropdownController : AjaxDropdownController<Country>
    {
        public CountryAjaxDropdownController(IRepo<Country> repo)
            : base(repo)
        {
        }
    }

    public class HobbyAjaxDropdownController : AjaxDropdownController<Hobby>
    {
        public HobbyAjaxDropdownController(IRepo<Hobby> repo)
            : base(repo)
        {
        }
    }

    public class FoobarAjaxDropdownController : AjaxDropdownController<Foobar>
    {
        public FoobarAjaxDropdownController(IRepo<Foobar> repo)
            : base(repo)
        {
        }
    }

    public class AjaxDropdownController<T> : Controller where T : INameId
    {
        private readonly IRepo<T> repo;

        public AjaxDropdownController(IRepo<T> repo)
        {
            this.repo = repo;
        }

        public ActionResult GetItems(int? key)
        {
            var list = new List<SelectListItem> { new SelectListItem { Text = "not selected", Value = "" } };
            list.AddRange(
            repo.GetAll().Select(o => new SelectListItem
                                          {
                                              Text = o.Name,
                                              Value = o.Id.ToString(),
                                              Selected = o.Id == key
                                          }));
            return Json(list);
        }
    }
}